import React, { useState, useCallback, useEffect, useMemo } from 'react';
import Head from 'next/head';
import Image from 'next/image';
import { useDropzone, FileRejection } from 'react-dropzone';
import { 
  generatePhoto, 
  changeBackgroundColor, 
  generateLayout,  
  PhotoSize, 
  PhotoResult, 
  addWatermark 
} from '../api/photoService';
import { useAuth } from '../contexts/AuthContext'; 
import PaymentModal from '@/components/PaymentModal';
import AuthModal from '@/components/AuthModal';
import ImageModal from '@/components/ImageModal';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import Message from '@/components/Message';
import Overlay from '@/components/Overlay';
import { Popover } from '@headlessui/react'

// 将 sizeOptions 移到组件外部
const sizeOptions = [
  { id: 'yicun', label: '一寸（295x413）', width: 295, height: 413 },
  { id: 'ercun', label: '二寸（413x579）', width: 413, height: 579 },
  { id: 'xiaoercun', label: '小二寸（350x490）', width: 350, height: 490 },
  { id: 'dayicun', label: '大一寸（390x567）', width: 390, height: 567 },
  { id: 'teacher', label: '教师资格证（295x413）', width: 295, height: 413 },
  { id: 'accounting', label: '初级会计考试（295x413）', width: 295, height: 413 },
  { id: 'civilservant', label: '国家公务员考试（295x413）', width: 295, height: 413 },
];

const Home: React.FC = () => {
  const [file, setFile] = useState<File | null>(null);
  // const [transparentPhotoUrl, setTransparentPhotoUrl] = useState<string | null>(null);
  const [backgroundColor, setBackgroundColor] = useState('#438EDB'); // 默认蓝色
  const [size, setSize] = useState<PhotoSize>(sizeOptions[0]);
  const [photoResult, setPhotoResult] = useState<PhotoResult | null>(null);
  // const [isPaid, setIsPaid] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  // const [originalPhotoResult, setOriginalPhotoResult] = useState<PhotoResult | null>(null);
  const [transparentBase64, setTransparentBase64] = useState<string | null>(null);

  const [showLoginRegister, setShowLoginRegister] = useState(false);
  const { user, token } = useAuth(); // 使用 useAuth hook
  // const router = useRouter();

  const [showPaymentModal, setShowPaymentModal] = useState(false); // 新增
  const [showAuthModal, setShowAuthModal] = useState(false);

  const [isProcessing, setIsProcessing] = useState(false);

  const [selectedSizeId, setSelectedSizeId] = useState(sizeOptions[0].id);

  const [modalImage, setModalImage] = useState<string | null>(null);

  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const [showOverlay, setShowOverlay] = useState(false);

  const [customColor, setCustomColor] = useState('#438EDB');

  useEffect(() => {
    // 检查用户是否已登录
    if (user) {
      // 删除未使用的设置
      // setIsLoggedIn(true);
      // setUsername(user.email);
    }
  }, [user]);

  // const handleLogout = () => {
  //   logout();
  //   setIsLoggedIn(false);
  //   setUsername('');
  // };

  const generatePreviewAndLayout = useCallback(async (file: File, color: string) => {
    if (!file) {
      setErrorMessage('没有选择件');
      return;
    }
    setIsLoading(true);
    setShowOverlay(true);
    try {
      const result = await generatePhoto(file, size, color);
      setPhotoResult(result);
      setTransparentBase64(result.transparentBase64);
      setBackgroundColor(color);
    } catch (error) {
      console.error('Error generating photo:', error);
      setErrorMessage('生成证件照失败，请重试。');
    } finally {
      setIsLoading(false);
      setShowOverlay(false);
    }
  }, [size]);

  const onDrop = useCallback(async (acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
    if (rejectedFiles.length > 0) {
      const rejection = rejectedFiles[0];
      if (rejection.errors[0]?.code === 'file-too-large') {
        setErrorMessage('文件大小超过5MB限制，请选择更小的文件。');
      } else if (rejection.errors[0]?.code === 'file-invalid-type') {
        setErrorMessage('只支持JPG和PNG格式的图片，请重新选择。');
      } else {
        setErrorMessage('文件上传失败，请重试。');
      }
      return;
    }

    if (acceptedFiles && acceptedFiles.length > 0) {
      const file = acceptedFiles[0];
      setErrorMessage(null);
      setFile(file);
      // 重置所有相关状态
      setPhotoResult(null);
      setTransparentBase64(null);
      setBackgroundColor('#438EDB'); // 重置为默认颜色
      setCustomColor('#438EDB');
      await generatePreviewAndLayout(file, '#438EDB');
    } else {
      setErrorMessage('未选择任何文件，请选择一张JPG或PNG格式的图片。');
    }
  }, [generatePreviewAndLayout]);

  const { getRootProps, getInputProps } = useDropzone({ 
    onDrop,
    accept: {
      'image/jpeg': ['.jpg', '.jpeg'],
      'image/png': ['.png']
    },
    maxSize: 5 * 1024 * 1024, // 5MB
    multiple: false
  });

  const applyBackgroundColor = useCallback(async (color: string) => {
    if (isProcessing || !transparentBase64 || color === backgroundColor) return;
    setIsProcessing(true);
    setShowOverlay(true);
    try {
      const newPreview = await changeBackgroundColor(transparentBase64, color);
      const newLayout = await generateLayout(newPreview, size);
      
      const previewWithWatermark = await addWatermark(newPreview);
      const layoutWithWatermark = await addWatermark(newLayout);
      
      const newPhotoResult: PhotoResult = {
        preview: previewWithWatermark,
        layout: layoutWithWatermark,
        originalPreview: newPreview,
        originalLayout: newLayout,
        transparentBase64: transparentBase64
      };

      setPhotoResult(newPhotoResult);
      setBackgroundColor(color);
    } catch (error) {
      console.error('Error changing background color:', error);
      setErrorMessage('更改背景颜色失败，请重试。');
    } finally {
      setIsProcessing(false);
      setShowOverlay(false);
    }
  }, [transparentBase64, size, backgroundColor, isProcessing]);

  const handleBackgroundColorChange = useCallback((color: string, isCustom: boolean = false) => {
    if (isCustom) {
      setCustomColor(color);
    } else {
      applyBackgroundColor(color);
    }
  }, [applyBackgroundColor]);

  const handleConfirmColor = useCallback((close: () => void) => {
    applyBackgroundColor(customColor);
    close(); // 关闭 Popover
  }, [customColor, applyBackgroundColor]);

  const handleSizeChange = useCallback((newSize: PhotoSize, newSizeId: string) => {
    setSize(newSize);
    setSelectedSizeId(newSizeId);
  }, []);

  // 将 size 相关的副作用移到组件顶
  useEffect(() => {
    const handleSizeEffect = async () => {
      if (file && transparentBase64) {
        await applyBackgroundColor(backgroundColor);
      }
    };

    handleSizeEffect();
  }, [size, file, backgroundColor, applyBackgroundColor, transparentBase64]);

  // const handlePayment = async () => {
  //   try {
  //     const success = await makePayment();
  //     if (success) {
  //       setIsPaid(true);
  //       alert('支付成功！');
  //       // 支付成功后，更新预览为无水印版本
  //       if (originalPhotoResult) {
  //         setPhotoResult({
  //           ...originalPhotoResult,
  //           preview: originalPhotoResult.originalPreview,
  //           layout: originalPhotoResult.originalLayout
  //         });
  //       }
  //     }
  //   } catch (error) {
  //     console.error('付失败:', error);
  //     alert('支付失败，请重试。');
  //   }
  // };

  // const handleDownload = (dataUrl: string, fileName: string) => {
  //   const link = document.createElement('a');
  //   link.href = dataUrl;
  //   link.download = fileName;
  //   document.body.appendChild(link);
  //   link.click();
  //   document.body.removeChild(link);
  // };

  // 使用 useMemo 来记忆化颜色选项，避免不必要的重新渲染
  const commonColors = useMemo(() => [
    { color: '#438EDB', label: '蓝色' },
    { color: '#FF0000', label: '红色' },
    { color: '#FFFFFF', label: '白色' },
    { color: '#81cfff', label: '浅蓝' },
    { color: '#960013', label: '深红' }
  ], []);

  const handlePaymentClick = async () => {
    if (user && token) {
      setShowPaymentModal(true);
    } else {
      setShowAuthModal(true);
    }
  };

  const handleTokenExpired = () => {
    setShowPaymentModal(false);
    setShowAuthModal(true);
  };

  const handleAuthSuccess = () => {
    setShowAuthModal(false);
    setShowPaymentModal(true);
  };

  const handleAuthModalClose = (success: boolean) => {
    setShowLoginRegister(false);
    if (success) {
      // 登录成功后的操作，例如刷新用户数据
    }
  };

  // const handlePaymentSuccess = () => {
  //   setIsPaid(true);
  //   setShowPaymentModal(false);
  //   // 不更新预览图，保持带水印的版本
  // };

  const openImageModal = (imageSrc: string) => {
    setModalImage(imageSrc);
  };

  const closeImageModal = () => {
    setModalImage(null);
  };

  return (
    <div className="min-h-screen flex flex-col bg-gray-50">
      <Head>
        <title>证件术师 - 在线证件照制作工具</title>
        <meta name="description" content="证件魔术师是一款专业的在线证件照制作具，支持多种尺寸和背景颜色，快速生成高质量证件照。" />
        <meta name="keywords" content="证件照,证件照制作,在线证件照,证件照生成器,证件照背景修改,证件照尺寸调整" />
      </Head>

      <Header setShowLoginRegister={setShowLoginRegister} />

      <main className="flex-grow">
        <div className="max-w-6xl mx-auto px-4 py-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-6">在线证件照作工具</h1>
          <p className="text-lg text-gray-700 mb-8">使用证件魔术师，轻松制作各种尺寸的证件照，支持背景颜色修改和智能美化。</p>
          <div className="bg-white shadow-lg rounded-lg p-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              <div>
                <div 
                  {...getRootProps()} 
                  className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center mb-4 hover:border-blue-500 transition duration-150 relative"
                  style={{ height: '300px' }}
                >
                  <input {...getInputProps()} />
                  {isLoading ? (
                    <div className="flex flex-col items-center justify-center h-full">
                      <svg className="animate-spin h-10 w-10 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <p className="mt-2 text-sm text-gray-500">正在处理，请稍候...</p>
                    </div>
                  ) : file ? (
                    <Image
                      src={URL.createObjectURL(file)}
                      alt="Uploaded Preview"
                      layout="fill"
                      objectFit="contain"
                      className="rounded-lg"
                    />
                  ) : (
                    <div className="flex flex-col items-center justify-center h-full">
                      <svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
                      </svg>
                      <p className="mt-2 text-sm text-gray-500">点击或拖放文件到这里上传</p>
                      <p className="text-xs text-gray-400 mt-1">支持 JPG、PNG 格式，文件大小不超过 5MB</p>
                    </div>
                  )}
                </div>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">照片尺寸：</label>
                    <select
                      value={selectedSizeId}
                      onChange={(e) => {
                        const selectedOption = sizeOptions.find(option => option.id === e.target.value);
                        if (selectedOption) {
                          handleSizeChange({ width: selectedOption.width, height: selectedOption.height }, selectedOption.id);
                        }
                      }}
                      className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                      {sizeOptions.map((option) => (
                        <option key={option.id} value={option.id}>
                          {option.label}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">照片底色：</label>
                    <div className="flex items-center space-x-3 mb-2">
                      <Popover className="relative">
                        {({ close }) => ( // 删除未使用的 open 参数
                          <>
                            <Popover.Button
                              className="w-12 h-12 rounded-full border-4 border-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 overflow-hidden shadow-md hover:shadow-lg transition-all duration-200"
                              style={{ backgroundColor: backgroundColor }}
                            >
                              <span className="sr-only">选择颜色</span>
                            </Popover.Button>

                            <Popover.Panel className="absolute z-10 mt-2 w-64">
                              <div className="bg-white border border-gray-200 rounded-lg shadow-lg p-4">
                                <input
                                  type="color"
                                  value={customColor}
                                  onChange={(e) => handleBackgroundColorChange(e.target.value, true)}
                                  className="w-full h-32 mb-2 cursor-pointer"
                                />
                                <div className="flex justify-between items-center mt-2">
                                  <div className="flex items-center">
                                    <span className="w-5 h-5 rounded-full border border-gray-300 mr-2" style={{ backgroundColor: customColor }}></span>
                                    <span className="text-xs font-medium text-gray-700">{customColor.toUpperCase()}</span>
                                  </div>
                                  <div className="flex space-x-2">
                                    <button
                                      onClick={() => close()} // 使用 close 函数
                                      className="px-2 py-1 text-xs bg-gray-100 text-gray-800 rounded hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-400 focus:ring-offset-2 transition-colors duration-200"
                                    >
                                      取消
                                    </button>
                                    <button
                                      onClick={() => handleConfirmColor(close)} // 传递 close 函数给 handleConfirmColor
                                      className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-colors duration-200"
                                      disabled={isProcessing}
                                    >
                                      确认
                                    </button>
                                  </div>
                                </div>
                              </div>
                            </Popover.Panel>
                          </>
                        )}
                      </Popover>
                      <div className="flex space-x-2">
                        {commonColors.map((colorObj) => (
                          <button
                            key={colorObj.color}
                            onClick={() => handleBackgroundColorChange(colorObj.color)}
                            className="w-8 h-8 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 relative group transition-transform hover:scale-110"
                            style={{ backgroundColor: colorObj.color }}
                            disabled={isProcessing}
                          >
                            <span className="sr-only">{colorObj.label}</span>
                            <span className="absolute bottom-full left-1/2 transform -translate-x-1/2 bg-gray-800 text-white text-xs rounded py-1 px-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200 whitespace-nowrap">
                              {colorObj.label}
                            </span>
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div>
                {photoResult ? (
                  <div className="space-y-4">
                    <div>
                      <h4 className="text-lg font-semibold text-gray-800 mb-2">预览：</h4>
                      <div 
                        className="relative w-full h-64 border border-gray-200 rounded-lg overflow-hidden cursor-pointer group"
                        onClick={() => openImageModal(photoResult.preview)}
                      >
                        <Image 
                          src={photoResult.preview}
                          alt="Preview" 
                          layout="fill" 
                          objectFit="contain"
                        />
                        <div className="absolute top-2 right-2 bg-black bg-opacity-50 rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                          <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
                          </svg>
                        </div>
                      </div>
                    </div>
                    <div>
                      <h4 className="text-lg font-semibold text-gray-800 mb-2">排版照片：</h4>
                      <div 
                        className="relative w-full h-64 border border-gray-200 rounded-lg overflow-hidden cursor-pointer group"
                        onClick={() => openImageModal(photoResult.layout)}
                      >
                        <Image 
                          src={photoResult.layout}
                          alt="Layout" 
                          layout="fill" 
                          objectFit="contain"
                        />
                        <div className="absolute top-2 right-2 bg-black bg-opacity-50 rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                          <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
                          </svg>
                        </div>
                      </div>
                    </div>
                    <div className="mt-6">
                      <button
                        onClick={handlePaymentClick}
                        className="w-full bg-gradient-to-r from-sky-400 to-cyan-300 text-white py-2 px-4 rounded-lg font-medium hover:from-sky-500 hover:to-cyan-400 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 transition duration-150"
                      >
                        下载
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="flex items-center justify-center h-full">
                    <p className="text-gray-500 text-center">上传图片后，预览将显示在这里</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </main>

      <Footer />

      {showLoginRegister && (
        <AuthModal onClose={handleAuthModalClose} />
      )}

      {/* 新增 PaymentModal */}
      {showPaymentModal && (
        <PaymentModal
          onClose={() => setShowPaymentModal(false)}
          onPaymentSuccess={() => {
            // setIsPaid(true);
            // 不要在这里关闭支付模态框，让用户看到下载完成提示
            // setShowPaymentModal(false);
          }}
          onTokenExpired={handleTokenExpired}
          photoResult={photoResult}
        />
      )}

      {showAuthModal && (
        <AuthModal
          onClose={(success) => {
            setShowAuthModal(false);
            if (success) handleAuthSuccess();
          }}
        />
      )}

      {modalImage && (
        <ImageModal
          src={modalImage}
          alt="Enlarged Image"
          onClose={closeImageModal}
        />
      )}

      {errorMessage && (
        <Message 
          message={errorMessage} 
          type="error" 
          onClose={() => setErrorMessage(null)} 
        />
      )}

      {showOverlay && <Overlay />}
    </div>
  );
};

export default Home;
